package com.hangzhou.welbeing.welbeinginstrument.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hangzhou.welbeing.welbeinginstrument.R;
import com.hangzhou.welbeing.welbeinginstrument.base.MyApplication;
import com.hangzhou.welbeing.welbeinginstrument.bean.RegistrationBean;
import com.hangzhou.welbeing.welbeinginstrument.bean.VerificationCodeBean;
import com.hangzhou.welbeing.welbeinginstrument.config.RBConstants;
import com.hangzhou.welbeing.welbeinginstrument.tool.PhoneFormatCheckUtils;
import com.hangzhou.welbeing.welbeinginstrument.utils.Utils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 时间 2017 年 08 月 21.
 * 作者 Administrator  刘传华
 * 公司 杭州惟君医疗科技有限公司
 * 包名 com.hangzhou.welbeing.pregnant.welbeing_pregnant.activity
 * 工程名 welbeing_pregnant
 * @desc  注册
 */
public class RegistrationActivity extends Activity {
    private static final String TAG ="RegistrationActivity" ;
    @Bind(R.id.activity_registration_iv_return)
    ImageView activityRegistrationIvReturn;
    @Bind(R.id.activity_registration_rl_title)
    RelativeLayout activityRegistrationRlTitle;
    @Bind(R.id.activity_registration_et_phone_number)
    EditText activityRegistrationEtPhoneNumber;
    @Bind(R.id.activity_registration_et_verification_code)
    EditText activityRegistrationEtVerificationCode;
    @Bind(R.id.activity_registration_tv_send_verification_code)
    TextView activityRegistrationTvSendVerificationCode;
    @Bind(R.id.activity_registration_et_password)
    EditText activityRegistrationEtPassword;
    @Bind(R.id.activity_registration_rl_next_step)
    RelativeLayout activityRegistrationRlNextStep;

    @Bind(R.id.activity_registration_ll_phone_and_password)
    LinearLayout activityRegistrationllPhoneAndPassword;

    private int i = RBConstants.COUNTDOWN;
    private Timer timer = null;
    private TimerTask task = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_registration);
        ButterKnife.bind(this);
        Utils.setStatusBar(this,false,false);
        Utils.setStatusTextColor(true,this);
        //手机号
        activityRegistrationEtPhoneNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String PhoneNumber = charSequence.toString().trim();
                if(PhoneNumber.length()>10){
                    if(PhoneFormatCheckUtils.isPhoneLegal(PhoneNumber)){
                        Toast.makeText(RegistrationActivity.this,"手机号格式正确",Toast.LENGTH_LONG).show();
                    }
                }
            }
            @Override
            public void afterTextChanged(Editable editable) {}
        });

    }

    @OnClick({R.id.activity_registration_iv_return, R.id.activity_registration_tv_send_verification_code, R.id.activity_registration_rl_next_step})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.activity_registration_iv_return:
                Intent intent2 = new Intent(RegistrationActivity.this,EntranceActivity.class);
                startActivity(intent2);
                finish();
                overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
                break;
            case R.id.activity_registration_tv_send_verification_code: //发送验证码
                String PhoneNumber = activityRegistrationEtPhoneNumber.getText().toString().trim();
                if(!TextUtils.isEmpty(PhoneNumber)){
                    GetVerificationCode(PhoneNumber);
                    countdown();
                }else{
                    Toast.makeText(RegistrationActivity.this,"请输入手机号",Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.activity_registration_rl_next_step:
                //手机号
                String registration_PhoneNumber = activityRegistrationEtPhoneNumber.getText().toString().trim();
                //验证码
                String registration_VerificationCode = activityRegistrationEtVerificationCode.getText().toString().trim();
                //密码
                String registration_Password =  activityRegistrationEtPassword.getText().toString().trim();
                if(!TextUtils.isEmpty(registration_PhoneNumber)){
                    if(!TextUtils.isEmpty(registration_VerificationCode)){
                        if(!TextUtils.isEmpty(registration_Password)){
                            registration(registration_PhoneNumber,registration_VerificationCode,registration_Password);
                        }else{
                            Toast.makeText(RegistrationActivity.this,"请输入密码",Toast.LENGTH_LONG).show();
                        }
                    }else{
                        Toast.makeText(RegistrationActivity.this,"请输入验证码",Toast.LENGTH_LONG).show();
                    }
                }else{
                    Toast.makeText(RegistrationActivity.this,"请输入手机号",Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

    //注册
    private void registration(String registration_PhoneNumber, String registration_VerificationCode, String registration_Password) {
        OkHttpUtils
                .post()
                .url(RBConstants.SERVER_URL+RBConstants.REGISTRATION)
                .addParams("tel", registration_PhoneNumber)
                .addParams("password", registration_Password)
                .addParams("code", registration_VerificationCode)
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String parseNetworkResponse = response.body().string();
                        //Log.e(TAG,"parseNetworkResponse==registration======"+parseNetworkResponse);
                        Gson gson = new Gson();
                        final RegistrationBean registrationBean =   gson.fromJson(parseNetworkResponse, RegistrationBean.class);
                        MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    if(registrationBean.errorCode == 200){
                                        Toast.makeText(RegistrationActivity.this,"注册成功",Toast.LENGTH_LONG).show();
                                        Intent intent2 = new Intent(RegistrationActivity.this,LoginActivity.class);
                                        startActivity(intent2);
                                        finish();
                                        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
                                    }else{
                                        Toast.makeText(RegistrationActivity.this,registrationBean.errorMessage,Toast.LENGTH_LONG).show();
                                    }

                                }
                            });
                        return null;
                    }
                    @Override
                    public void onError(Call call, Exception e, int id) {}
                    @Override
                    public void onResponse(Object response, int id) {}
                });
    }
    //发送验证码
    private void GetVerificationCode(String phoneNumber) {
        OkHttpUtils
                .get()
                .url(RBConstants.SERVER_URL+RBConstants.SENDDUANXIN)
                .addParams("tel", phoneNumber)
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String parseNetworkResponse = response.body().string();
                       // Log.e(TAG,"parseNetworkResponse========"+parseNetworkResponse);
                        Gson gson = new Gson();
                        final VerificationCodeBean verificationCodeBean =  gson.fromJson(parseNetworkResponse, VerificationCodeBean.class);
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    if(verificationCodeBean.errorCode == 200){
                                        Toast.makeText(RegistrationActivity.this,"验证码发送成功",Toast.LENGTH_LONG).show();
                                    }else{
                                        Toast.makeText(RegistrationActivity.this,verificationCodeBean.errorMessage,Toast.LENGTH_LONG).show();
                                    }

                                }
                            });
                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });
    }

    //倒计时
    private void countdown() {
        startTime();
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            if (i > 0) {
                activityRegistrationTvSendVerificationCode.setText("重新发送" + i + "s");
                startTime();
            } else {
                stopTime();
                activityRegistrationTvSendVerificationCode.setText("获取验证码");
                i = 60;
            }
        }
    };
    public void startTime() {
           timer = new Timer();
        task = new TimerTask() {
            @Override
            public void run() {
                i--;
                Message message = mHandler.obtainMessage();
                message.arg1 = i;
                mHandler.sendMessage(message);
            }
        };
        timer.schedule(task, 1000);
    }

    public void stopTime() {
        timer.cancel();
    }

}
